<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/27
 * Time: 14:40
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

class FinanceBank extends BaseModel
{
    protected $pk = 'bank_id';

    protected $insert = ['create_by'];

    protected $append = ['name_acc'];

    protected function getNameAccAttr()
    {
        return $this->getData('name') . ' ... ' . substr($this->getData('account'), -4);
    }

    /**
     * 获取所有银行账号信息
     * @return static[]
     * @date 2021/01/12
     * @author longli
     */
    public static function getAll()
    {
        return static::where("status", self::IS_YES)
            ->order("is_default desc, sort desc, bank_id desc")
            ->select();
    }

    /**
     * 设置默认银行
     * @param int|self $bank 银行id，银行
     * @param bool $force 强制设置
     * @return bool
     * @date 2021/01/22
     * @author longli
     */
    public static function setDefault($bank, $force = false)
    {
        $bank = self::getObj($bank);
        if(empty($bank)) return false;
        if(!$force && $bank->is_default == self::IS_YES) return true;
        static::where("bank_id", ">", 0)
            ->update(['is_default' => self::IS_NO]);
        static::where("bank_id", $bank->bank_id)->update(['is_default' => self::IS_YES]);
        return true;
    }

    /**
     * 获取默认银行账号
     * @return static
     * @date 2021/01/22
     * @author longli
     */
    public static function getDefault()
    {
        return static::get(['is_default' => static::IS_YES]);
    }
}
